package com.example.demotest.demos.bens;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.jcraft.jsch.JSchException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;


import java.io.*;
import java.net.URL;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

public class FileInput {

    public static List<SSHClient> getFileSshClientList() throws IOException, JSchException {

        List<SSHClient> sshClientList = new ArrayList<>();

        ClassPathResource resource = new ClassPathResource("addressDatas.json");
        InputStream inputStream = resource.getInputStream();


        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        JSONObject jsonObject = null;
        try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader);) {
            StringBuffer content = new StringBuffer();
            String msg = null;
            while ((msg=bufferedReader.readLine())!=null){
                content.append(msg);
            }

            System.out.println("读取addressDatas文件成功:" + content.toString());
            jsonObject = JSONObject.parseObject(content.toString());
        } catch (IOException e) {
            System.out.println("读取addressDatas文件失败:" + e);
        }
        if(jsonObject == null){
            System.out.println("读取addressDatas文件内容为空:");
            return sshClientList;
        }
        if (jsonObject != null && jsonObject.containsKey("addressDatas")) {
            JSONArray addressDatas = jsonObject.getJSONArray("addressDatas");
            for (int i = 0; i < addressDatas.size(); i++) {
                JSONObject addressData = addressDatas.getJSONObject(i);
                System.out.println(addressData.toJSONString());
                if (StringUtils.isEmpty(addressData.getString("ip")) ||
                        StringUtils.isEmpty(addressData.getString("port")) ||
                        StringUtils.isEmpty(addressData.getString("username")) ||
                        StringUtils.isEmpty(addressData.getString("password"))) {
                    continue;
                }
                SSHClient sshClient = new SSHClient();
                sshClient.setHost(addressData.getString("ip")).
                        setPort(addressData.getInteger("port")).
                        setUsername(addressData.getString("username")).
                        setPassword(addressData.getString("password"));
                sshClientList.add(sshClient);
            }
        }
        return sshClientList;
    }

}
